package com.example.a001.part33;

import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

public class VolleySupport {
    private final String TAG = getClass().getName();
    private static VolleySupport sSupport;
    private RequestQueue mQueue;
    private Gson mGson;

    private VolleySupport() {
        mQueue = ApplicationContext.getsQueue();
        mGson = new Gson();
    }

    public static VolleySupport getInstance() {
        if (sSupport == null) {
            synchronized (VolleySupport.class) {
                if (sSupport == null) {
                    sSupport = new VolleySupport();
                }
            }
        }
        return sSupport;
    }

    public <ResultType> void sendRequest4Get(
            String action,
            String parameter,
            final Class<ResultType> resultT) {
        mQueue.add(new JsonObjectRequest(Request.Method.GET,
                "https://suggest.taobao.com/" + action + parameter,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.d(TAG, "请求成功：" + jsonObject.toString());
                        try {
                            // 处理淘宝接口的特殊JSONP格式
                            String jsonStr = jsonObject.toString();
                            if (jsonStr.startsWith("define(") && jsonStr.endsWith(")")) {
                                jsonStr = jsonStr.substring(7, jsonStr.length() - 1);
                            }
                            ResultType resultType = mGson.fromJson(jsonStr, resultT);
                            EventBus.getDefault().post(resultType);
                        } catch (Exception e) {
                            Log.e(TAG, "JSON解析错误: " + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, "请求失败: " + volleyError.getMessage());
                        volleyError.printStackTrace();
                    }
                }));
    }
}
